<!--
 * @author  dumeng
 新建文档
-->
<template>
  <div class="courseware-create">
    <el-dialog
      v-el-drag-dialog
      :lock-scroll="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="visible"
      :title="info.subjectName ? '重新转码' : '新建文档'"
      center
      width="600px"
      custom-class="courseware-create-dialog"
      @close="$emit('close')"
    >
      <section v-loading="loading" class="courseware-create-main">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="form">
          <template v-if="uploadFile.oldfile && uploadFile.oldfile.name">
            <el-form-item label="转码失败原因" prop="fileType">
              <el-input v-model="info.transcodeFailReason" type="textarea" disabled :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入内容" />
            </el-form-item>
          </template>
          <el-form-item label="文档类型" prop="fileType" size="medium">
            <el-radio-group v-model="form.fileType" :disabled="!!info.id" @change="changeFileAccept">
              <el-radio v-for="item in dict['WJLX']" :key="item.dictValue" :label="item.dictValue">{{ item.dictName }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="uploadFile.oldfile && uploadFile.oldfile.name">
            <el-form-item label="原文档">
              <div class="select-data">
                {{ uploadFile.oldfile.name }}
              </div>
              <el-button size="mini" type="text" @click="preview.state = true">查看</el-button>
              <el-button size="mini" type="text" @click="downLoad">下载</el-button>
            </el-form-item>
          </template>
          <el-form-item :label="info.id ? '重新上传文档' : '文档上传'" prop="courseId">
            <div v-if="!uploadFile.file" class="selectbtn" @click="uploadFile.showUpload = true">开始上传</div>
            <template v-else>
              <div :key="form.courseId" class="select-data">
                {{ uploadFile.file.name }}
                <i class="el-icon-close" @click="clearFile" />
              </div>
            </template>
            <Upload
              v-if="uploadFile.showUpload"
              ref="upload"
              :accept="uploadFile.accept"
              :limit="1"
              :show-chunks="true"
              :multiple="false"
              :chunk-size="uploadFile.chunksize"
              @close="uploadFile.showUpload = false"
              @success="uploadSuccess"
            >
              <div slot="tip" class="upload-tip">
                <i class="el-icon-info" />
                : 只能上传：{{ form.fileType | filterTip }}
              </div>
            </Upload>
            <p v-if="info.id" style="color: red;margin:0;"><i class="el-icon-info" />如果不重新上传文档，表示再次对原文档进行转码</p>
          </el-form-item>
          <el-form-item label="是否允许下载" prop="isDownAttachment">
            <el-radio-group v-model="form.isDownAttachment">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="文档名称" prop="subjectName">
            <el-input v-model.trim="form.subjectName" maxlength="100" placeholder="" />
          </el-form-item>
          <el-form-item label="文档封面">
            <image-upload
              :key="uploadImg.imagecropperKey"
              v-model="form.subjectImg"
              :is-oss="isOss"
              :preview-id="uploadImg.viewId"
              :forever="true"
              :width="190"
              :view="uploadImg.view"
              :height="254"
              :no-circle="true"
              :no-rotate="false"
              lang-type="zh"
              @changeOssPath="
                (path) => {
                  uploadImg.viewId = path
                }
              "
            />
          </el-form-item>
          <el-form-item label="文档分类" prop="subjectClassify">
            <el-cascader
              ref="classify"
              v-model="form.subjectClassify"
              style="width:100%"
              clearable
              :props="createClassifyProps"
              :options="classifyOptions"
            />
          </el-form-item>
        </el-form>
      </section>
      <section class="courseware-create-footer">
        <el-button style="padding: 10px 30px;" @click="$emit('close')">取 消</el-button>
        <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
      </section>
    </el-dialog>
    <el-dialog
      v-if="preview.state"
      v-el-drag-dialog
      :fullscreen="isFull"
      custom-class="courseware-preview"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="preview.state"
      title="预览"
      center
      width="600px"
      @close="preview.state = false"
    >
      <div class="full">
        <el-button size="small" type="primary" icon="el-icon-full-screen" @click="isFull = !isFull">{{ isFull ? '取消全屏' : '全屏' }}</el-button>
      </div>
      <coursewareware-preview v-if="preview.state" :is-full="isFull" show-type="before" :type="preview.fileType" :file-id="preview.fileId" />
    </el-dialog>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import Upload from './upload/index'
import { getClassifyTree, getDictByCode, insert, update } from '../api/createCourseware'
import { specialText } from '@/utils/validate'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import coursewarewarePreview from './CoursewarePreview'
export default {
  name: 'Create',
  components: { Upload, coursewarewarePreview, ImageUpload },
  directives: { elDragDialog },
  filters: {
    filterTip(fileType) {
      if (fileType === 'WJLX_PDF') {
        return 'PDF文件'
      } else if (fileType === 'WJLX_WORD') {
        return 'WORD文件'
      } else if (fileType === 'WJLX_TXT') {
        return 'TXT文件'
      } else if (fileType === 'WJLX_PPT') {
        return 'PPT文件'
      } else if (fileType === 'WJLX_EXCEL') {
        return 'EXCEL文件'
      } else if (fileType === 'WJLX_ANY') {
        return '任意文件'
      }
    }
  },
  props: {
    info: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      loading: false,
      form: {
        id: '',
        subjectImg: '',
        subjectName: '',
        subjectClassify: '',
        fileType: 'WJLX_PDF',
        subjectType: 'KCLX02',
        courseId: '',
        subjectDuration: '',
        isDownAttachment: '0'
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入文档名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 100 个字', trigger: 'blur' }
        ],
        subjectClassify: [{ required: true, message: '请选择文档分类', trigger: 'change' }],
        fileType: [{ required: true, message: '请选择文档类型', trigger: 'change' }],
        courseId: [{ required: true, message: '请上传文档', trigger: 'change' }]
      },
      dict: [], // 字典列表
      inputDuration: true, // 是否禁用输入文档时长
      createClassifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      classifyOptions: [],
      uploadFile: {
        showUpload: false,
        accept: '.pdf',
        chunksize: 10 * 1024 * 1024,
        file: '',
        oldfile: ''
      },
      preview: {
        state: false,
        fileId: '',
        fileType: 1
      },
      isFull: false, // 预览是否全屏
      visible: true
    }
  },
  watch: {
    'form.classifyIds': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    this.getClassifyOption()
      .then(() => {
        // for (const i in this.form) {
        //   this.form[i] = this.info[i]
        // }
        // if (!this.form.fileType) {
        //   this.form.fileType = 'KCLX01'
        // }
        // this.changeFileAccept()
        this.$nextTick(() => {
          this.$refs['form'].clearValidate()
        })
        if (this.info.subjectName) {
          this.uploadFile.oldfile = { name: this.info.subjectName }
        }
        this.preview.fileId = this.info.courseId || ''
        this.preview.fileType = this.info.fileType || ''
        console.log(this.info)
        this.loading = false
      })
      .catch((err) => {
        console.log('errList', err)
      })
  },
  mounted() {
    this.getDict('WJLX')
  },
  methods: {
    downLoad() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-DOCUMENT/document/file/download?id=' + this.info.courseId
      link.setAttribute('download', this.uploadFile.oldfile.name)
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    clearFile() {
      this.uploadFile.file = ''
      if (!this.info.id) {
        this.form.courseId = ''
      }
      this.form.subjectDuration = ''
    },
    /**
     * 格式化文档时长单位
     */
    fomatterTimeAndPage(t) {
      if (this.form.fileType === 'KCLX02') {
        return '页'
      } else {
        const fTime = t || 0
        let time = parseInt(fTime) + '秒'
        if (parseInt(fTime) > 60) {
          var second = parseInt(fTime) % 60
          var min = parseInt(fTime / 60)
          time = min + '分' + second + '秒'

          if (min > 60) {
            min = parseInt(fTime / 60) % 60
            var hour = parseInt(parseInt(fTime / 60) / 60)
            time = hour + '小时' + min + '分' + second + '秒'

            if (hour > 24) {
              hour = parseInt(parseInt(fTime / 60) / 60) % 24
              var day = parseInt(parseInt(parseInt(fTime / 60) / 60) / 24)
              time = day + '天' + hour + '小时' + min + '分' + second + '秒'
            }
          }
        }
        return time
      }
    },
    /**
     * 获取文档分类
     */
    getClassifyOption() {
      this.loading = true
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL07' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * 切换文档类型动态修改文件上传组件文件限制
     */
    changeFileAccept() {
      if (this.form.fileType === 'WJLX_PDF') {
        this.uploadFile.accept = '.pdf'
      } else if (this.form.fileType === 'WJLX_WORD') {
        this.uploadFile.accept = '.docx,.doc'
      } else if (this.form.fileType === 'WJLX_TXT') {
        this.uploadFile.accept = '.txt'
      } else if (this.form.fileType === 'WJLX_PPT') {
        this.uploadFile.accept = '.ppt,.pptx'
      } else if (this.form.fileType === 'WJLX_EXCEL') {
        this.uploadFile.accept = '.xls,.xlsx'
      } else if (this.form.fileType === 'WJLX_ANY') {
        this.uploadFile.accept = ''
      }
      this.clearFile()
    },
    onSubmint() {
      if (this.info.id) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params.transcodeStatus = params.fileType === 'KCLX02' ? '3' : '2'
            if (params.subjectClassify instanceof Array) {
              params['subjectClassify'] = params.subjectClassify.length > 0 ? params.subjectClassify[params.subjectClassify.length - 1] : ''
            }
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$emit('close')
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error update!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['subjectClassify'] = this.form.subjectClassify.length > 0 ? this.form.subjectClassify[this.form.subjectClassify.length - 1] : ''
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$emit('close')
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    uploadSuccess(id, files) {
      if (id) {
        this.form.courseId = id
        this.form.subjectName = files[0].name.substring(0, files[0].name.lastIndexOf('.'))
        this.uploadFile.file = files[0]
        if (this.form.fileType === 'WJLX_PDF' && files[0].totalPages && files[0].totalPages > 0) {
          this.form.subjectDuration = files[0].totalPages
        }
        this.uploadFile.showUpload = false
      }
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
            this.$forceUpdate()
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.courseware-create {
  .courseware-create-dialog .el-dialog__body {
    height: 600px !important;
    overflow-y: auto;
    .courseware-create-main {
      height: 90%;
      overflow-y: auto;
    }
  }
  .select-data {
    display: inline-block;
    background: rgba(246, 246, 246, 1);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    padding: 0 10px;
    margin-right: 5px;
    margin-bottom: 8px;

    i {
      cursor: pointer;
      padding-left: 5px;
    }
  }

  .selectbtn {
    display: inline-block;
    width: 120px;
    background: rgba(255, 255, 255, 1);
    @include border-color(1px, dotted, $mainColor);
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    @include font-color($mainColor);
    text-align: center;
    cursor: pointer;
  }

  .courseware-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
  .courseware-preview {
    .el-dialog__body {
      position: relative;
      .full {
        position: absolute;
        width: 100px;
        height: 58px;
        right: 50px;
        top: -58px;
        display: flex;
        align-items: center;
        text-align: right;
      }
    }
  }
}
</style>
